// import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

import odoo from '@/odooapi'
// const { login, logout, getInfo } = rpc

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  async smsSend({ commit }, payload) {
    // const { username, password } = userInfo
    const res = await odoo.rpc.sms_send(payload)
    return new Promise((resolve, reject) => {
      resolve(res)
    })
  },

  async smsBack({ commit }, payload) {
    const code = await odoo.rpc.sms_back(payload)
    return new Promise((resolve, reject) => {
      resolve(code)
    })
  },

  async smsLogin({ commit, dispatch }, payload) {
    const response = await odoo.rpc.sms_login(payload)
    return dispatch('afterLogin', response)
  },

  async afterLogin({ commit }, response) {
    return new Promise((resolve, reject) => {
      const { code, data } = response
      if (code === 20000) {
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      } else {
        console.log('xxxx, afterLogin,reject,', response)
        reject(response)
      }
    })
  },

  // user login
  async login({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo
    const response = await odoo.login({
      username: username.trim(),
      password: password
    })
    console.log('xxxxx, login,', dispatch)
    return dispatch('afterLogin', response)

    // return new Promise((resolve, reject) => {
    //   odoo
    //     .login({ username: username.trim(), password: password })
    //     .then(response => {
    //       const { data } = response
    //       commit('SET_TOKEN', data.token)
    //       setToken(data.token)
    //       resolve()
    //     })
    //     .catch(error => {
    //       reject(error)
    //     })
    // })
  },

  resetAll({ commit }) {
    commit('SET_TOKEN', '')
    commit('SET_ROLES', [])
    commit('SET_NAME', '')
    commit('SET_AVATAR', '')
    commit('SET_INTRODUCTION', '')
    removeToken()
    resetRouter()
  },

  async register({ commit, dispatch }, payload) {
    // const { mobile, code, username, password } = payload
    const response = odoo.rpc.register(payload)
    return new Promise((resolve, reject) => {
      response
        .then(res => {
          dispatch('resetAll')
          resolve(res)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  async resetPassword({ commit, dispatch }, payload) {
    // const { mobile, code, password } = payload
    // console.log('xxxx, resetPassword, ', mobile, code, password)

    const response = odoo.rpc.sms_reset_password(payload)

    return new Promise((resolve, reject) => {
      response
        .then(res => {
          dispatch('resetAll')
          resolve(res)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  async changePassword({ commit, dispatch }, payload) {
    const { oldPsw, newPsw } = payload
    const User = odoo.env('res.users')

    const response = User.change_password(oldPsw, newPsw)

    return new Promise((resolve, reject) => {
      response
        .then(res => {
          dispatch('resetAll')
          resolve(res)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      odoo
        .getInfo(state.token)
        .then(response => {
          const { data } = response

          if (!data) {
            reject('Verification failed, please Login again.')
          }

          const { roles, name, avatar, introduction } = data

          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject('getInfo: roles must be a non-null array!')
          }

          commit('SET_ROLES', roles)
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          commit('SET_INTRODUCTION', introduction)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      odoo
        .logout(state.token)
        .then(() => {
          dispatch('resetAll')

          // reset visited views and cached views
          // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
          dispatch('tagsView/delAllViews', null, { root: true })

          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {
        root: true
      })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
